/*
 * @author Guillermo Adrian Salguero Ortega
 */
package formula_urjc;

import clases.Carrera;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;

public class ListaCarrerasForm extends javax.swing.JFrame {
 
    DefaultTableModel dtmEjemplo;
        public ListaCarrerasForm(){
            initComponents();
        //Llenamos el modelo
        dtmEjemplo = new DefaultTableModel(null,getColumnas());
 
        setFilas();
 
        this.tablaCarreras.setModel(dtmEjemplo);
        this.setSize(500, 500);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        
    }
  
 private ArrayList<Carrera> listaCarreras;
 
    //Encabezados de la tabla
    private String[] getColumnas()
    {
          String columna[] = new String[]{"Nombre","Circuito"};
          return columna;
    }
 
    private void setFilas()
    {
      try{
        this.listaCarreras = Carrera.leerCarrera(); 
        if (!(listaCarreras.isEmpty())){
         // Recorro la lista ocn un foreach
            for(Carrera carreraAux : listaCarreras) {
             // Recupero las variables
                String nombre = carreraAux.getNombre();
                String circuito = carreraAux.getCircuito();
                Object objeto[]={nombre, circuito};
                dtmEjemplo.addRow(objeto);
            }
        }
       }catch (NullPointerException ex){
            System.out.println("Listado de circuitos vacio");
       }
       
    }

   
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        labelEscu = new java.awt.Label();
        altaB = new javax.swing.JButton();
        bajaB = new javax.swing.JButton();
        modificarB = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaCarreras = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        labelEscu.setName(""); // NOI18N
        labelEscu.setText("Lista Carreras");

        altaB.setText("Alta");
        altaB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                altaBActionPerformed(evt);
            }
        });

        bajaB.setText("Borrar");
        bajaB.setToolTipText("");
        bajaB.setEnabled(false);
        bajaB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bajaBActionPerformed(evt);
            }
        });

        modificarB.setText("Modificar");
        modificarB.setEnabled(false);
        modificarB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                modificarBActionPerformed(evt);
            }
        });

        tablaCarreras.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Nombre", "Circuito"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaCarreras.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                seleccionarItem(evt);
            }
        });
        jScrollPane1.setViewportView(tablaCarreras);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(labelEscu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGap(205, 205, 205)
                            .addComponent(altaB)
                            .addGap(18, 18, 18)
                            .addComponent(bajaB)
                            .addGap(18, 18, 18)
                            .addComponent(modificarB))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(labelEscu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 76, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(altaB)
                    .addComponent(bajaB)
                    .addComponent(modificarB))
                .addGap(58, 58, 58))
        );

        labelEscu.getAccessibleContext().setAccessibleName("Lista de carreras");
        labelEscu.getAccessibleContext().setAccessibleDescription("");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(49, 49, 49))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void altaBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_altaBActionPerformed
        // Contamos el numero de columnas dado que el maximo de carreras son 5
        int rowCount = this.tablaCarreras.getRowCount();
        if (rowCount <5){// Si hay menos de 5 vamos al alta
                AltaCarrera altaCarr = new AltaCarrera();
                this.setVisible(false);
                altaCarr.setVisible(true);
        }else{// Si hay 5 mostramos warning
        javax.swing.JOptionPane. showMessageDialog (this, "El numero maximo de Carreras del Mundial son 5");
        }
        

    }//GEN-LAST:event_altaBActionPerformed

    private void bajaBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bajaBActionPerformed
    
        int row = this.tablaCarreras.getSelectedRow();
        BorrarCarrera borrarCarrera = new BorrarCarrera(this, true,row);
        
        this.setVisible(false);
        borrarCarrera.setVisible(true);
    }//GEN-LAST:event_bajaBActionPerformed
   
    private void modificarBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modificarBActionPerformed
        int row = this.tablaCarreras.getSelectedRow();
        Carrera carreAux = this.listaCarreras.get(row);

        ModificarCarrera modCarrera = new ModificarCarrera(carreAux,row);
        this.setVisible(false);
        modCarrera.setVisible(true);
        
    }//GEN-LAST:event_modificarBActionPerformed

    private void seleccionarItem(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_seleccionarItem
        this.bajaB.setEnabled(true);
        this.modificarB.setEnabled(true);
    }//GEN-LAST:event_seleccionarItem

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ListaEscuForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ListaEscuForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ListaEscuForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ListaEscuForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
       
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ListaEscuForm().setVisible(true);
            }
        });  
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton altaB;
    private javax.swing.JButton bajaB;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private java.awt.Label labelEscu;
    private javax.swing.JButton modificarB;
    private javax.swing.JTable tablaCarreras;
    // End of variables declaration//GEN-END:variables
}
